package com.cipta.lomob;

import java.util.ArrayList;
import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONObject;

import tv.lomob.api.Lomob;
import tv.lomob.api.LomobResponseHandler;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cipta.lomob.adapter.AdapterUsers;
import com.cipta.lomob.base.BaseActivity;
import com.cipta.lomob.components.CropCircleTransformation;
import com.cipta.lomob.model.Users;
import com.cipta.lomob.utils.AnimationHelper;
import com.cipta.lomob.utils.SampleData;
import com.squareup.picasso.Picasso;

public class ConnectFriendsActivity extends BaseActivity{
	private ListView lvFriends;
	private ProgressBar indicator;
	private View view;
	private TextView txtConnectTitle;
	
	private ArrayList<Users> listHeader;
	private LinkedList<Users> listUser;
	private LinkedList<Users> tempUsers;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_connect_friends);
		
		initializeViews();
		initializeLibs();
		initializeProcess();
		initializeActions();
	}
	
	@Override
	public void initializeViews() {
		// TODO Auto-generated method stub
		super.initializeViews();
		
		lvFriends = (ListView)findViewById(R.id.lvConnectedFriends);
		indicator = (ProgressBar)findViewById(R.id.pbIndicator);
		txtConnectTitle = (TextView)findViewById(R.id.txtConnectedFriendsTitle);
	}
	
	@Override
	public void initializeLibs() {
		// TODO Auto-generated method stub
		super.initializeLibs();
		listHeader = new ArrayList<Users>();
		listUser = new LinkedList<Users>();
		tempUsers = new LinkedList<Users>();
	}
	
	@Override
	public void initializeProcess() {
		// TODO Auto-generated method stub
		super.initializeProcess();
		
		indicator.setVisibility(View.GONE);
		
		Users friends = null;
		Users users = null;
		
		Lomob.loadSuggestFriends(LomobManager.getInstance().getUser().optString("token"), new LomobResponseHandler() {
			
			@Override
			public void onSuccess(JSONObject result) {
				prepareSuggestFriends(result.optJSONArray("data"));
			}
			
			@Override
			public void onError(String message) {
				try{
					Log.i("LOMOB", message);
				}catch(Exception ex){
					ex.printStackTrace();
				}
				
			}
		});

		for (int i = 0; i < SampleData.sampleFriends.length; i++) {
			users = new Users();
			users.setName(SampleData.sampleFriends[i][0]);
			users.setTotalMomments(Integer.parseInt(SampleData.sampleFriends[i][1]));
			users.setTotalFollowing(Integer.parseInt(SampleData.sampleFriends[i][2]));
			users.setTotalFollowers(Integer.parseInt(SampleData.sampleFriends[i][3]));
			users.setFollowing(Boolean.parseBoolean(SampleData.sampleFriends[i][4]));
			users.setAvatar("");
			listUser.add(users);
		}
		
		for (int i = 0; i < listHeader.size(); i++) {
			view = getLayoutInflater().inflate(R.layout.inf_connected_friends, null);
			ImageView imgAvatar = (ImageView)view.findViewById(R.id.inf_img_connected_friends_avatar);
			TextView txtName = (TextView)view.findViewById(R.id.inf_txt_connected_friends_name);
			TextView txtTotalMomments = (TextView)view.findViewById(R.id.inf_txt_connected_friends_momments);
			TextView txtFollowers = (TextView)view.findViewById(R.id.inf_txt_connected_friends_followers);
			TextView txtFollowings = (TextView)view.findViewById(R.id.inf_txt_connected_friends_following);
			Button btnAction = (Button)view.findViewById(R.id.btn_connected_friends_action);
			btnAction.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					showInviteAlert();
				}
			});

			txtName.setText(listHeader.get(i).getName());
			txtTotalMomments.setText("Momments "+listHeader.get(i).getTotalMomments());
			txtFollowings.setText("Following "+listHeader.get(i).getTotalFollowing());
			txtFollowers.setText("Follower "+listHeader.get(i).getTotalFollowers());
			
			//set action here
			btnAction.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View viewButton) {
					view.setVisibility(View.GONE);
				}
			});
			
			if (i==listHeader.size()-1) {
				View inviteText = getLayoutInflater().inflate(R.layout.view_invite_friends, null);
				LinearLayout lnInviteText = (LinearLayout)view.findViewById(R.id.lnViewInvite);
				TextView txtInviteTitle = (TextView)view.findViewById(R.id.txt_invite_friends);
				lnInviteText.addView(inviteText);
			}
			
			lvFriends.addHeaderView(view);
		}
		
		
		AdapterUsers adapterUsers = new AdapterUsers(ConnectFriendsActivity.this, listUser);
		lvFriends.setAdapter(adapterUsers);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.connect_friends_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_next:
			PopularUserActivity.toPopularActivity(ConnectFriendsActivity.this);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public static void toConnectFriendsActivity(Activity activity){
		activity.startActivity(new Intent(activity, ConnectFriendsActivity.class));
	}
	
	//prepare sugges
	private void prepareSuggestFriends(JSONArray listSuggest){
		int total = listSuggest.length();
		Users user = null;
		for(int i=0;i<total;i++){
			user = new Users();
			user.setId(listSuggest.optJSONObject(i).optString("id"));
			user.setName(listSuggest.optJSONObject(i).optString("firstname") + " " + listSuggest.optJSONObject(i).optString("lastname"));
			user.setTotalMomments(listSuggest.optJSONObject(i).optInt("sum_moment"));
			user.setTotalFollowing(listSuggest.optJSONObject(i).optInt("sum_following"));
			user.setTotalFollowers(listSuggest.optJSONObject(i).optInt("sum_moment"));
			user.setFollowing(false);
			user.setAvatar(listSuggest.optJSONObject(i).optString("avatar"));
			tempUsers.add(user);
		}
		
		ImageView imgAvatar;
		TextView txtName = null;
		TextView txtTotalMomments = null;
		TextView txtFollowers = null;
		TextView txtFollowings = null;
		Button btnAction = null;
		
		//now pass data to view
		for (int j = 0; j < 2; j++) {
			ViewHolder holder = null;
				holder = new ViewHolder();
				view = getLayoutInflater().inflate(R.layout.inf_connected_friends, null);
				holder.imgAvatar = (ImageView)view.findViewById(R.id.inf_img_connected_friends_avatar);
				holder.txtName = (TextView)view.findViewById(R.id.inf_txt_connected_friends_name);
				holder.txtTotalMomments = (TextView)view.findViewById(R.id.inf_txt_connected_friends_momments);
				holder.txtFollowers = (TextView)view.findViewById(R.id.inf_txt_connected_friends_followers);
				holder.txtFollowings = (TextView)view.findViewById(R.id.inf_txt_connected_friends_following);
				holder.btnAction = (Button)view.findViewById(R.id.btn_connected_friends_action);				
				

//			imgAvatar.setImageResource(listHeader.get(i).getAvatar());
			holder.txtName.setText(tempUsers.getFirst().getName());
			holder.txtTotalMomments.setText("Momments "+tempUsers.getFirst().getTotalMomments());
			holder.txtFollowings.setText("Following "+tempUsers.getFirst().getTotalFollowing());
			holder.txtFollowers.setText("Follower "+tempUsers.getFirst().getTotalFollowers());
			//set tempUser
			holder.user = tempUsers.getFirst();
			holder.btnAction.setTag(view);
			Picasso.with(ConnectFriendsActivity.this).load(tempUsers.getFirst().getAvatar()).placeholder(R.drawable.user1).transform(new CropCircleTransformation()).into(holder.imgAvatar);
			
			view.setTag(holder);
			//now remove object from list
			tempUsers.removeFirst();
			
			//set action here
			holder.btnAction.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(final View viewButton) {
					final Animation fadeout = AnimationHelper.createFadeoutAnimation();
					final View v = (View) viewButton.getTag();
					final ViewHolder holder = (ViewHolder) v.getTag();
					//send to server
					Lomob.followUser(LomobManager.getInstance().getUser().optString("token"), holder.user.getId(), new LomobResponseHandler() {
						
						@Override
						public void onSuccess(JSONObject result) {
							Log.i("API", "success follow");
						}
						
						@Override
						public void onError(String message) {
							Log.e("API", message);
						}
					});
					
					
					fadeout.setAnimationListener(new Animation.AnimationListener() {
						
						@Override
						public void onAnimationStart(Animation arg0) {
						
						}
						
						@Override
						public void onAnimationRepeat(Animation arg0) {
							
						}
						
						@Override
						public void onAnimationEnd(Animation arg0) {
							
							if(tempUsers.size() !=0){
								holder.txtName.setText(tempUsers.getFirst().getName());
								holder.txtTotalMomments.setText("Momments "+tempUsers.getFirst().getTotalMomments());
								holder.txtFollowings.setText("Following "+tempUsers.getFirst().getTotalFollowing());
								holder.txtFollowers.setText("Follower "+tempUsers.getFirst().getTotalFollowers());
								Picasso.with(ConnectFriendsActivity.this).load(tempUsers.getFirst().getAvatar()).placeholder(R.drawable.user1).transform(new CropCircleTransformation()).into(holder.imgAvatar);
								holder.btnAction.setTag(v);
								holder.user = tempUsers.getFirst();
								v.setTag(holder);
								tempUsers.removeFirst();		
							}else{
								lvFriends.removeHeaderView(v);
							}
						}
					});
					v.startAnimation(fadeout);
				}
			});
			
			lvFriends.addHeaderView(view);
		}
	}
	
	static class ViewHolder{
		ImageView imgAvatar;
		TextView txtName;
		TextView txtTotalMomments;
		TextView txtFollowers;
		TextView txtFollowings;
		Button btnAction;
		Users user;
	}
	
	private void showInviteAlert(){
		final Dialog dialog = new Dialog(ConnectFriendsActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_invite_friends);
		Button btnOk = (Button)dialog.findViewById(R.id.btn_dialog_invite_);
		btnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		dialog.show();
	}
}
